package cn.zh.npro.Fragment;

import android.app.Dialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.formatter.XAxisValueFormatter;
import com.github.mikephil.charting.interfaces.datasets.ILineDataSet;
import com.github.mikephil.charting.utils.ViewPortHandler;
import com.lzy.okhttputils.OkHttpUtils;
import com.lzy.okhttputils.callback.StringCallback;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import cn.zh.npro.Adapter.Gpladapter;
import cn.zh.npro.Adapter.HgAdapter;
import cn.zh.npro.Item.CITem;
import cn.zh.npro.Item.HgItem;
import cn.zh.npro.MyApplication;
import cn.zh.npro.R;
import cn.zh.npro.Util.BaseUrl;
import cn.zh.npro.Util.Loading;
import cn.zh.npro.Util.MyMarkerView;
import cn.zh.npro.Util.ToastUtil;
import okhttp3.Call;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Created by WYN on 2018/2/28 0028.
 */

public class HgFragment extends Fragment{
    LineChart mLineChart,mLineChartt;

    TextView hdata,hfhtype,hgra,tytxt;
    LinearLayout tyline;

    //记录返回的商品数据
    CITem fciTem=null;
    //筛选
    //判断弹窗是否可以删除
    boolean isdele=true;
    //弹窗队列
    ArrayList<PopupWindow> popus=new ArrayList<PopupWindow>();
    Gpladapter gpladapter;
    //商品类别数据
    ArrayList<CITem>ciTems=new ArrayList<CITem>();
    Calendar c ;//
    int  mYear,mMonth; // 获取当前年份

    //数据
    ArrayList<HgItem>  hgItems=new ArrayList<>();
    ListView ghflist;
    HgAdapter hgAdapter=null;

    private Dialog LDialog;

    ArrayList<String>date=new ArrayList<>();
    ArrayList<Float> score= new ArrayList<>();
    int type=0;
    TextView empty;
    boolean isfirst=true;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view=LayoutInflater.from(getActivity()).inflate(R.layout.hg_layout,null,false);
        c = Calendar.getInstance();
        mYear = c.get(Calendar.YEAR);
        mMonth = c.get(Calendar.MONTH) + 1;
        inithf(view);
        getGetProductRanking();
        return view;
        }


    private void inithf(View view){
        mLineChart=view.findViewById(R.id.gline_chart);
        mLineChartt=view.findViewById(R.id.gline_chartt);
        empty=view.findViewById(R.id.empty);
        ghflist=view.findViewById(R.id.ghflist);
        hdata = view.findViewById(R.id.hdata);
        hfhtype=view.findViewById(R.id.hfhtype);
        hgra=view.findViewById(R.id.hgra);
        hdata.setText("排名");
        hfhtype.setText("商品名/销售额");
        hgra.setText("环比");
        hgAdapter=new HgAdapter(getActivity(),hgItems);
        ghflist.setAdapter(hgAdapter);
        tytxt=view.findViewById(R.id.tytxt);
        tyline=view.findViewById(R.id.tyline);
        tyline.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                    getPo();
                    getclss();
                 }
             });
        ghflist.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {

                getGdtail(hgItems.get(i).getGoodsID());
            }
         });
        }





    private void initLineChart(){
        List<Entry> entries = new ArrayList<>();
        entries.clear();
        for (int i = 0; i < score.size(); i++) {
            float data = score.get(i);
            entries.add(new Entry(data, i));
          }
        LineDataSet dataSet = new LineDataSet(entries, "");
        dataSet.setColor(Color.parseColor("#45a6d9"));// 每个点之间线的颜色，还有其他几个方法，自己看
        ArrayList<ILineDataSet> lineDataSets = new ArrayList<ILineDataSet>();
        lineDataSets.add(dataSet); // add the datasets
        LineData lineData = new LineData(date,lineDataSets);
        lineData.setValueTextSize(15);
        dataSet.setLineWidth(2.0f);
        dataSet.setCircleSize(4f);
        dataSet.setColor(Color.parseColor("#3498DB"));
        dataSet.setCircleColor(Color.parseColor("#3498DB"));
        dataSet.setCircleColorHole(Color.parseColor("#3498DB"));
        mLineChart.setDescription(null);
        lineData.setDrawValues(false);
        mLineChart.setBackgroundColor(Color.WHITE);
        mLineChart.setNoDataText("暂无数据");
        mLineChart.setDrawGridBackground(true);
        mLineChart.setGridBackgroundColor(Color.WHITE);
        mLineChart.setDrawBorders(false);
        mLineChart.setTouchEnabled(true);
        mLineChart.setDragEnabled(true);
        mLineChart.setScaleEnabled(true);
        mLineChart.setScaleXEnabled(true);
        mLineChart.setScaleYEnabled(false);
        mLineChart.setPinchZoom(true);
        mLineChart.setDoubleTapToZoomEnabled(false);
        mLineChart.setDragDecelerationEnabled(true);
        mLineChart.setDragDecelerationFrictionCoef(0.9f);
        dataSet.setHighlightEnabled(true);
        dataSet.setDrawHighlightIndicators(false);
        XAxis xAxis = mLineChart.getXAxis();
        YAxis yAxis = mLineChart.getAxisLeft();
        mLineChart.getAxisRight().setEnabled(false);
        float ratio = (float) date.size()/(float) 6;
        if (ratio>2.0){
            ratio=2;
          }
        mLineChart.zoom(ratio,1f,0,0);
        mLineChart.getViewPortHandler().setMinMaxScaleX(2,2);
        mLineChart.animateX(1500);
        yAxis.setAxisLineColor(Color.WHITE);
        yAxis.setLabelCount(3, false);
        yAxis.setAxisMinValue(0);
        xAxis.setDrawGridLines(false);
//        xAxis.setLabelRotationAngle(15);
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
        xAxis.setValueFormatter(new XAxisValueFormatter() {
            @Override
            public String getXValue(String s, int i, ViewPortHandler viewPortHandler) {
                if (type==1){
                String year=s.substring(0,4);
                String yue=s.substring(4);
                s=year+"-"+yue;
                 }
                return s;
             }
         });

        Legend l = mLineChart.getLegend();
        l.setEnabled(false);
        mLineChart.setMarkerView(new MyMarkerView(getActivity(), R.layout.custom_marker_view));    // 点击数据点显示的pop，有俩默认的，MarkerImage：一张图片，MarkerView:一个layout布局,也可以自己定义.这里这个是我自定义的一个MarkerView。
        mLineChart.setData(lineData);
        if (mLineChart.getData().getYMax()==0){
            mLineChart.getAxisLeft().setAxisMaxValue(20f);
            mLineChart.notifyDataSetChanged();
          }
        }


    private void initLineChartt(){
        List<Entry> entries = new ArrayList<>();
        entries.clear();
        for (int i = 0; i < score.size(); i++){
            float data = score.get(i);
            entries.add(new Entry(data, i));
        }
        LineDataSet dataSet = new LineDataSet(entries, "");
        dataSet.setColor(Color.parseColor("#45a6d9"));// 每个点之间线的颜色，还有其他几个方法，自己看
        ArrayList<ILineDataSet> lineDataSets = new ArrayList<ILineDataSet>();
        lineDataSets.add(dataSet); // add the datasets
        LineData lineData = new LineData(date,lineDataSets);
        lineData.setValueTextSize(15);
        dataSet.setLineWidth(2.0f);
        dataSet.setCircleSize(4f);
        dataSet.setColor(Color.parseColor("#3498DB"));
        dataSet.setCircleColor(Color.parseColor("#3498DB"));
        dataSet.setCircleColorHole(Color.parseColor("#3498DB"));
        mLineChartt.setDescription(null);
        lineData.setDrawValues(false);
        mLineChartt.setBackgroundColor(Color.WHITE);
        mLineChartt.setNoDataText("暂无数据");
        mLineChartt.setDrawGridBackground(true);
        mLineChartt.setGridBackgroundColor(Color.WHITE);
        mLineChartt.setDrawBorders(false);
        mLineChartt.setTouchEnabled(true);
        mLineChartt.setDragEnabled(true);
        mLineChartt.setScaleEnabled(true);
        mLineChartt.setScaleXEnabled(true);
        mLineChartt.setScaleYEnabled(false);
        mLineChartt.setPinchZoom(true);
        mLineChartt.setDoubleTapToZoomEnabled(false);
        mLineChartt.setDragDecelerationEnabled(true);
        mLineChartt.setDragDecelerationFrictionCoef(0.9f);
        dataSet.setHighlightEnabled(true);
        dataSet.setDrawHighlightIndicators(false);
        XAxis xAxis = mLineChartt.getXAxis();
        YAxis yAxis = mLineChartt.getAxisLeft();
        mLineChartt.getAxisRight().setEnabled(false);
        float ratio = (float) date.size()/(float) 6;
        if (ratio>2.0){
            ratio=2;
        }
        mLineChartt.zoom(ratio,1f,0,0);
        mLineChartt.getViewPortHandler().setMinMaxScaleX(2,2);
        mLineChartt.animateX(1500);
        yAxis.setAxisLineColor(Color.WHITE);
        yAxis.setLabelCount(3, false);
        yAxis.setAxisMinValue(0);
        xAxis.setDrawGridLines(false);
//        xAxis.setLabelRotationAngle(15);
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
        xAxis.setValueFormatter(new XAxisValueFormatter() {
            @Override
            public String getXValue(String s, int i, ViewPortHandler viewPortHandler) {
                if (type==1){
                    String year=s.substring(0,4);
                    String yue=s.substring(4);
                    s=year+"-"+yue;
                }
                return s;
            }
        });
        Legend l = mLineChartt.getLegend();
        l.setEnabled(false);
        mLineChartt.setData(lineData);
        mLineChartt.setMarkerView(new MyMarkerView(getActivity(), R.layout.custom_marker_view));    // 点击数据点显示的pop，有俩默认的，MarkerImage：一张图片，MarkerView:一个layout布局,也可以自己定义.这里这个是我自定义的一个MarkerView。
      }

    //获取商品排名报表
    public void getGetProductRanking(){
          type=0;
          String classid="0";
          if (null!=fciTem){
            classid=fciTem.getClassID();
            }
          int mo=mMonth-1;
        String st="";
          if (mo<10){
              st = "0"+mo;
           }else {
              st=mo+"";
          }
           String ym=mYear+st;
        OkHttpUtils.get(BaseUrl.GetProductRanking)
                .params("classid",classid)
                .params("top","10")
                .params("yearmonth",ym)
                .execute(new StringCallback() {
                    @Override
                    public void onResponse(boolean isFromCache, String s, Request request, @Nullable Response response) {
                        System.out.println("---------------->商品排名==="+s);
                        try {
                            JSONObject js=new JSONObject(s);
                            boolean State=js.getBoolean("State");
                            if (State){
                               boolean Flag=js.getBoolean("Flag");
                               if (Flag){
                                 JSONArray ja=js.getJSONArray("Data");
                                  date.clear();
                                  score.clear();
                                   hgItems.clear();
                                   isfirst=true;
                                 for (int i=0;i<ja.length();i++){
                                     JSONObject ji=ja.getJSONObject(i);
                                     String GoodsID=ji.getString("GoodsID");
                                     String GoodsName=ji.getString("GoodsName");
                                     String ClassId=ji.getString("ClassId");
                                     String YearMonth=ji.getString("YearMonth");
                                     double SellCount=ji.getDouble("SellCount");
                                     String Pr=ji.getString("Pr");
                                     String PrePr=ji.getString("PrePr");
                                     date.add(GoodsName);
                                     score.add((float)SellCount);
                                     HgItem hgItem=new HgItem(GoodsID,GoodsName,ClassId,YearMonth,SellCount,Pr,PrePr);
                                     hgItems.add(hgItem);
                                     if (SellCount==0){
                                     }else {
                                         isfirst=false;
                                     }
                                   }
                                   System.out.println("----------->date===="+date.size()+"======"+score.size());
                                   hgAdapter.notifyDataSetChanged();
                                   if (isfirst){
                                       mLineChartt.setVisibility(View.GONE);
                                       if (score.size()==0){
                                           empty.setVisibility(View.VISIBLE);
                                           mLineChart.setVisibility(View.GONE);
                                       }else {
                                           empty.setVisibility(View.GONE);
                                           mLineChart.setVisibility(View.VISIBLE);
                                           initLineChart();
                                       }
                                   }else {
                                       mLineChart.setVisibility(View.GONE);
                                       if (score.size()==0){
                                           empty.setVisibility(View.VISIBLE);
                                           mLineChartt.setVisibility(View.GONE);
                                       }else {
                                           empty.setVisibility(View.GONE);
                                           mLineChartt.setVisibility(View.VISIBLE);
                                           initLineChartt();
                                       }
                                   }
                               }else {
                                   empty.setVisibility(View.VISIBLE);
                                   mLineChart.setVisibility(View.GONE);
                               }
                            }else {
                                mLineChart.setVisibility(View.GONE);
                                empty.setVisibility(View.VISIBLE);
                                }

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                    }
                    @Override
                    public void onError(boolean isFromCache, Call call, @Nullable Response response, @Nullable Exception e) {
                        super.onError(isFromCache, call, response, e);
                    }
                });
              }







    //弹窗

    public  void getPo(){
        isdele=true;
        View vpa = LayoutInflater.from(getActivity()).inflate(R.layout.gaa_layout, null, false);
        WindowManager wm = (WindowManager) getActivity()
                .getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics outMetrics = new DisplayMetrics();
        wm.getDefaultDisplay().getMetrics(outMetrics);
        int  mScreenWitdh = outMetrics.widthPixels;
        final ImageView gaa=vpa.findViewById(R.id.gaa_back);

        ListView gaa_list=vpa.findViewById(R.id.gaa_list);

        gpladapter = new Gpladapter(getActivity(),ciTems);
        gaa_list.setAdapter(gpladapter);

        gaa_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                  if (null==ciTems.get(i).getChildClass()){
                      fciTem=ciTems.get(i);
                      tytxt.setText(fciTem.getClassName());
                      popus.get(0).dismiss();
                      getGetProductRanking();
                      return;
                    }
                if (ciTems.get(i).getChildClass().length()!=0){
                    getPodata(ciTems.get(i).getChildClass());
                  }else {
                    fciTem=ciTems.get(i);
                    tytxt.setText(fciTem.getClassName());
                    popus.get(0).dismiss();
                    getGetProductRanking();
                }
              }
        });
        final PopupWindow popupWindowga = new PopupWindow(vpa, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
        popupWindowga.setFocusable(true);
        popupWindowga.setOutsideTouchable(true);
        popupWindowga.setBackgroundDrawable(new ColorDrawable(Color.GRAY));
        popupWindowga.getContentView().setFocusableInTouchMode(true);
        popupWindowga.getContentView().setFocusable(true);
        popupWindowga.setAnimationStyle(R.style.popwin_anim_style);
        gaa.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                popupWindowga.dismiss();
            }
        });

        popupWindowga.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                if (isdele) {
                    if (popus.size()>0) {
                        popus.remove((popus.size() - 1));
                    }
                }
            }
          });

        popus.add(popupWindowga);
        popupWindowga.showAtLocation(getActivity().findViewById(R.id.hg_layout), Gravity.NO_GRAVITY, 0, 0);
     }






    //获取商品类别请求
    public void getclss(){
        LDialog= Loading.createLoadingDialog(getActivity(),"加载中...");
        MyApplication mapp= (MyApplication)getActivity(). getApplication();
        SharedPreferences sp = mapp.getSp();
        OkHttpUtils.get(BaseUrl.getGoodsClass+"?UserId="+ sp.getString("uid",""))
                .execute(new StringCallback() {
                    @Override
                    public void onResponse(boolean isFromCache, String s, Request request, @Nullable Response response) {
                        try {
                            JSONObject js=new JSONObject(s);
                            boolean state=js.getBoolean("State");
                            Loading.closeDialog(LDialog);
                            if (state){
                                JSONArray ja=js.getJSONArray("Res");
                                ciTems.clear();
                                CITem ciTem0=new CITem("","全部","","",null);
                                ciTems.add(ciTem0);
                                for (int i=0;i<ja.length();i++){
                                    JSONObject ji=ja.getJSONObject(i);
                                    String ClassID=ji.getString("ClassID");
                                    String ClassName=ji.getString("ClassName");
                                    String FatherId=ji.getString("FatherId");
                                    String ClassID2=ji.getString("ClassID2");
                                    JSONArray ChildClass=ji.getJSONArray("ChildClass");
                                    CITem ciTem=new CITem(ClassID,ClassName,FatherId,ClassID2,ChildClass);
                                    ciTems.add(ciTem);
                                }
                                gpladapter.notifyDataSetChanged();

                            }else {
                                String msg=js.getString("msg");
                                ToastUtil.showLong(getActivity(),msg);
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                    @Override
                    public void onError(boolean isFromCache, Call call, @Nullable Response response, @Nullable Exception e) {
                        super.onError(isFromCache, call, response, e);
                    }
                });
              }




    public void getPodata(JSONArray ja){
        final ArrayList<CITem> arrciTems=new ArrayList<CITem>();
        for (int i=0;i<ja.length();i++){
            try {
                JSONObject ji=ja.getJSONObject(i);
                String ClassID=ji.getString("ClassID");
                String ClassName=ji.getString("ClassName");
                String FatherId=ji.getString("FatherId");
                String ClassID2=ji.getString("ClassID2");
                JSONArray ChildClass=ji.getJSONArray("ChildClass");
                CITem ciTem=new CITem(ClassID,ClassName,FatherId,ClassID2,ChildClass);
                arrciTems.add(ciTem);
            }catch (JSONException e) {
                e.printStackTrace();
            }
        }
        View vpa = LayoutInflater.from(getActivity()).inflate(R.layout.gaa_layout, null, false);
        WindowManager wm = (WindowManager) getActivity()
                .getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics outMetrics = new DisplayMetrics();
        wm.getDefaultDisplay().getMetrics(outMetrics);

        int  mScreenWitdh = outMetrics.widthPixels;
        ImageView gaa=vpa.findViewById(R.id.gaa_back);
        ListView gaa_list=vpa.findViewById(R.id.gaa_list);

        Gpladapter gpladapter = new Gpladapter(getActivity(),arrciTems);
        gaa_list.setAdapter(gpladapter);
        gaa_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                if (arrciTems.get(i).getChildClass().length()==0){
                    fciTem=arrciTems.get(i);
                    tytxt.setText(fciTem.getClassName());
                    isdele=false;
                    for (int j=0;j<popus.size();j++){
                        popus.get(j).dismiss();
                    }
                    popus.clear();
                    getGetProductRanking();
                }else {
                    getPodata(arrciTems.get(i).getChildClass());
                }
            }
        });
        final PopupWindow popupWindowga = new PopupWindow(vpa, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
        popupWindowga.setFocusable(true);
        popupWindowga.setOutsideTouchable(true);
        popupWindowga.setBackgroundDrawable(new ColorDrawable(Color.GRAY));
        popupWindowga.getContentView().setFocusableInTouchMode(true);
        popupWindowga.getContentView().setFocusable(true);
        popupWindowga.setAnimationStyle(R.style.popwin_anim_style);

        gaa.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                popupWindowga.dismiss();
            }
        });
        popupWindowga.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                if (isdele) {
                    popus.remove((popus.size() - 1));
                }
            }
        });
        popus.add(popupWindowga);
        popupWindowga.showAtLocation(getActivity().findViewById(R.id.hg_layout), Gravity.NO_GRAVITY, 0, 0);
       }



    public void getGdtail(String gid){
        System.out.println("--------------------gid==="+gid);
        type=1;
        OkHttpUtils.get(BaseUrl.GetProductReport)
                .params("goodsId",gid)
                .execute(new StringCallback() {
                    @Override
                    public void onResponse(boolean isFromCache, String s, Request request, @Nullable Response response) {
                        System.out.println("----------------->商品销售额=="+s);

                        try {
                            JSONObject js=new JSONObject(s);
                            boolean State=js.getBoolean("State");
                            if (State){
                                JSONArray Data=js.getJSONArray("Data");
                                 date.clear();
                                 score.clear();
                                isfirst=true;
                                for (int i=0;i<Data.length();i++){
                                    JSONObject ji=Data.getJSONObject(i);
                                    String YearMonth=ji.getString("YearMonth");
                                    double SellCount=ji.getDouble("SellCount");
                                    date.add(YearMonth);
                                    score.add((float)SellCount);
                                    if (SellCount==0){
                                    }else {
                                        isfirst=false;
                                    }
                                  }
                                if (isfirst){
                                    mLineChartt.setVisibility(View.GONE);
                                    if (score.size()==0){
                                        empty.setVisibility(View.VISIBLE);
                                        mLineChart.setVisibility(View.GONE);
                                    }else {
                                        empty.setVisibility(View.GONE);
                                        mLineChart.setVisibility(View.VISIBLE);
                                        initLineChart();
                                    }
                                }else {
                                    mLineChart.setVisibility(View.GONE);
                                    if (score.size()==0){
                                        empty.setVisibility(View.VISIBLE);
                                        mLineChartt.setVisibility(View.GONE);
                                    }else {
                                        empty.setVisibility(View.GONE);
                                        mLineChartt.setVisibility(View.VISIBLE);
                                        initLineChartt();
                                    }
                                }
                              }
                           } catch (JSONException e) {
                              e.printStackTrace();
                           }
                         }
                    @Override
                    public void onError(boolean isFromCache, Call call, @Nullable Response response, @Nullable Exception e) {
                        super.onError(isFromCache, call, response, e);
                    }
                });
               }



    }
